#!/usr/bin/env python

from ftplib import *;
import StringIO, sys, getopt,os;

maxnum = 30
def err_usage():
    print 'usage: %s [-m num_of_news]'%sys.argv[0]
    sys.exit(1)

def fetchtext(text, num):
    ftp = FTP('thu.trueice.net')
    ftp.login()
    ftp.cwd('PopMusic/pub/Music/MP3')
    for line in ftp.nlst('-alst'):
        if line.find('whatsnew.')==-1:
            continue;
        if num == 0:
            break;
        else: num -= 1;
        parts = line.split();
        filename = parts[-1];
        try:
            ftp.retrbinary('RETR '+filename, text.write)
        except:
            print '!!! error processing :'+filename
        print 'getting file "%s" finished'%filename
    text.close()
    ftp.close()

def changeline(text):
    parent = ""
    playlist = open('playlist.m3u', 'w')
    for line in text.readlines():
        if line.startswith('pub/'):
            parent = line.strip()
            parent = parent.replace('pub/Music/MP3/','http://thu.trueice.net/music/')
        elif line.startswith('\t') and line.strip().lower().endswith('mp3'):
            playlist.write(parent+'/'+line.strip())
            playlist.write(os.linesep)
    playlist.close()
    
if __name__ == "__main__":
    opts, args = getopt.getopt(sys.argv[1:], 'm:')
    for optpair in opts:  # like this[('-d', ''), ('-k', '3')...]
        if optpair[0]=='-m':
            try:
                maxnum = int(optpair[1])
            except:
                err_usage()
            if maxnum ==-1:
                print "can't be -1!"
                sys.exit(1)

    NO_FETCH = False;
    try:
        text = open('whatsnew')
        print "do you want to re-fetch that file? [y/n]",
        answer = raw_input()
        text.close()
        if answer.lower().find('y')!=-1:
            text = open('whatsnew', 'wb')
            print 'old file cleared'
        else:
            NO_FETCH = True
    except:
        text = open('whatsnew', 'wb')

    if not NO_FETCH:
        fetchtext(text, maxnum)

    text = open('whatsnew')
    try:
        changeline(text)
    finally:
        text.close()

    
